//
//  CEMCRXJLCFListPreparePayControllerJuykET.m
//  Jlcf_ios
//
//  Created by 邓伟浩 on 2019/4/19.
//  Copyright © 2019 ski. All rights reserved.
//

#import "CEMCRXJLCFListPreparePayControllerJuykET.h"

#import "zCTafxJLCFListYuePayViewControllerFzNQRu.h"
#import "sHkPtEJLCFMineRequestozAYZs.h"
#import "XZHNOcJLCFMineBindCardViewControllerMRXeuQ.h"
#import "LdalypJLCFListPayOrderViewControllerRSNbkl.h"
#import "uuOBGoJLCFPreparePayInfoCellAjIsAk.h"
#import "vgxfqhJLCFMineTopUpViewControllerBVsVle.h"
#import "DTdkodJLCFRedPackageControllerALtAUS.h"

@interface CEMCRXJLCFListPreparePayControllerJuykET ()<UITextFieldDelegate>

@property (nonatomic, copy) NSString *amount;

// 选中的优惠券
@property (nonatomic, strong) FozWsFJLCFMineWelfareDataModelLetMnJ *welfare;

@property (nonatomic, strong) UITextField *HgalTPmoneyFieldNWNbOL;
@property (nonatomic, strong) UILabel *YBtbRUcanGetLabelfqnRMY;

@end

@implementation CEMCRXJLCFListPreparePayControllerJuykET

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"支付";
    self.tableView.frame = CGRectMake(0, NAVBAR_HEIGHT, FULL_WIDTH, FULL_HEIGHT - NAVBAR_HEIGHT);
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.backgroundColor = QTZ_Gray237;
    [self.tableView registerClass:[uuOBGoJLCFPreparePayInfoCellAjIsAk class] forCellReuseIdentifier:NSStringFromClass([uuOBGoJLCFPreparePayInfoCellAjIsAk class])];
    self.tableView.tableHeaderView = [self tableHeaderView];
    
    UIButton *limitBtn = [UIButton buttonWithType:0];
    [limitBtn setTitle:@"限额说明" forState:0];
    [limitBtn setTitleColor:[UIColor blackColor] forState:0];
    limitBtn.titleLabel.font = FONT(12);
    [limitBtn sizeToFit];
    [limitBtn addTarget:self action:@selector(handleLimit) forControlEvents:UIControlEventTouchUpInside];
    limitBtn.right = FULL_WIDTH - 20;
    limitBtn.centerY = NAVBAR_CENTER_Y;
    [self.navigationBar addSubview:limitBtn];
    
    [self addBottomView];
    
    [_HgalTPmoneyFieldNWNbOL becomeFirstResponder];
}

- (void)handleLimit {
    JLCFBaseWebViewController *webVC = [[JLCFBaseWebViewController alloc] init];
    webVC.url = QTZ_WEB_URL(@"bank_list.html");
    [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:webVC animated:YES];
}


- (void)addBottomView {
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(FitRealValue(180));
    }];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    UIView *acceptBackView = [[UIView alloc] init];
    [bottomView addSubview:acceptBackView];
    
    UIButton *acceptRuleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [acceptBackView addSubview:acceptRuleBtn];
    [acceptRuleBtn setImage:[UIImage imageNamed:@"icon_list_agree"] forState:UIControlStateNormal];
    [acceptRuleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(FitRealValue(30));
        make.left.mas_equalTo(acceptBackView.mas_left);
        make.centerY.mas_equalTo(acceptBackView);
    }];
    
    UIButton *ruleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [acceptBackView addSubview:ruleButton];
    NSString *acceptText = @"我同意并接受";
    NSMutableAttributedString *acceptAttrStr = [[NSMutableAttributedString alloc] initWithString:acceptText attributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:FONT(8)}];
    NSString *serviceText = @"《金鲤财富服务协议》";
    NSMutableAttributedString *serviceAttrStr = [[NSMutableAttributedString alloc] initWithString:serviceText attributes:@{NSForegroundColorAttributeName:Theme_Color, NSFontAttributeName:FONT(8)}];
    [acceptAttrStr appendAttributedString:serviceAttrStr];
    [ruleButton setAttributedTitle:acceptAttrStr forState:UIControlStateNormal];
    [ruleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(acceptRuleBtn.mas_right).offset(10);
        make.centerY.mas_equalTo(acceptRuleBtn.mas_centerY);
        make.right.mas_equalTo(acceptBackView.mas_right);
        make.height.mas_equalTo(15);
    }];
    [ruleButton addTarget:self action:@selector(toRule) forControlEvents:UIControlEventTouchUpInside];
    
    [acceptBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomView);
        make.top.mas_equalTo(bottomView);
        make.height.mas_equalTo(FitRealValue(80));
    }];
    
    UIButton *buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:buyBtn];
    buyBtn.backgroundColor = Theme_Color;
    buyBtn.titleLabel.font = FONT(15);
    [buyBtn setTitle:@"确认投资" forState:0];
    [buyBtn setTitleColor:QTZ_White forState:0];
    [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(bottomView);
        make.top.mas_equalTo(acceptBackView.mas_bottom);
    }];
    [buyBtn addTarget:self action:@selector(handleBuy) forControlEvents:UIControlEventTouchUpInside];
}

- (void)toRule {
    JLCFBaseWebViewController *webVC = [[JLCFBaseWebViewController alloc] init];
    webVC.url = QTZ_WEB_URL(@"service.html");
    [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:webVC animated:YES];
}

- (void)handleBuy {
    if (!self.amount) {
        [self showNotice:@"请输入投资金额!"];
        return;
    }
    
    //首先确定是否走余额支付
    if([[JLCFRegisterService shareService].userMoney integerValue] >= [_amount integerValue]){
        // 跳转到余额支付页面
        zCTafxJLCFListYuePayViewControllerFzNQRu *vc  = [zCTafxJLCFListYuePayViewControllerFzNQRu new];
        vc.amount = _amount;
        vc.proId = self.CUWORhdetailModelIRREMd.data.id;
        if (self.welfare) {
            vc.welfare = self.welfare;
        }
        [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:vc animated:YES];
    } else { // 跳转到银行卡支付
        //银行卡支付之前首先判断是否有银行卡可以使用
        [sHkPtEJLCFMineRequestozAYZs myCardWithparams:nil loadingInView:self.view success:^(SssHPaJLCFMYCardInfoModelHkAXvP *data) {
            if ([data.isBind isEqualToString:@"0"]) {
                // 前去绑定银行卡
                XZHNOcJLCFMineBindCardViewControllerMRXeuQ *vc = [XZHNOcJLCFMineBindCardViewControllerMRXeuQ new];
                vc.flFGIcbindCardmirovY = YES;
                vc.bindComplete = ^{
                    [self handleBuy];
                };
                [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:vc animated:YES];
            } else {
                // 前去支付
                LdalypJLCFListPayOrderViewControllerRSNbkl *vc = [LdalypJLCFListPayOrderViewControllerRSNbkl new];
                vc.cardinfo = data;
                vc.amount = self.amount;
                vc.proid = self.CUWORhdetailModelIRREMd.data.id;
                [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:vc animated:YES];
                if(self.welfare){
                    vc.welfare = self.welfare;
                }
                
            }
        } failure:^(NSString *error) {
            [self showNotice:error];
        }];
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return FitRealValue(120);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FULL_WIDTH, 10)];
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    uuOBGoJLCFPreparePayInfoCellAjIsAk *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([uuOBGoJLCFPreparePayInfoCellAjIsAk class]) forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.tBjReMtipsImageViewAreHYI.image = [UIImage imageNamed:@"icon_list_qianbao"];
        cell.edHyphtipsLabelTVYPVW.text = @"我的钱包";
        cell.NdgzxmdesLabelTTSqri.text = [NSString stringWithFormat:@"余额: ￥%@", [JLCFRegisterService shareService].userMoney];
        cell.QXqSRCrightImageViewWUkIEz.image = [UIImage imageNamed:@"icon_list_chargeRight"];
        cell.BHWzVXrightLabelHwIhQT.text = @"充值";
    } else {
        cell.tBjReMtipsImageViewAreHYI.image = [UIImage imageNamed:@"icon_list_youhui"];
        cell.edHyphtipsLabelTVYPVW.text = @"优惠券";
        cell.NdgzxmdesLabelTTSqri.text = self.welfare?[NSString stringWithFormat:@"-%@ 元", self.welfare.hbmoney]:@"未使用优惠券";
        cell.QXqSRCrightImageViewWUkIEz.image = [UIImage imageNamed:@"icon_list_youhuiRight"];
        cell.BHWzVXrightLabelHwIhQT.text = @"";
    }
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        [self makeCharge];
    } else {
        [self makeRedPackage];
    }
}

- (void)makeCharge {
    [sHkPtEJLCFMineRequestozAYZs myCardWithparams:nil loadingInView:self.view success:^(SssHPaJLCFMYCardInfoModelHkAXvP *data) {
        if ([data.isBind isEqualToString:@"0"]) {
            //前去绑定银行卡
            XZHNOcJLCFMineBindCardViewControllerMRXeuQ *vc = [XZHNOcJLCFMineBindCardViewControllerMRXeuQ new];
            vc.flFGIcbindCardmirovY = YES;
            vc.bindComplete = ^{
                [self makeCharge];
            };
            [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:vc animated:YES];
        } else {
            MineTopUpViewController *vc = [MineTopUpViewController new];
            vc.nEvvdBfullCardDatakvLLBq = data;
            [[JinLiCaiFuApplicationEntrace shareEntrance].currentNavController pushViewController:vc animated:YES];
        }
    } failure:^(NSString *error) {
        [self showNotice:error];
    }];
}

- (void)makeRedPackage {
    DTdkodJLCFRedPackageControllerALtAUS *red = [[DTdkodJLCFRedPackageControllerALtAUS alloc] init];
    red.CUWORhdetailModelIRREMd = self.CUWORhdetailModelIRREMd;
    red.amount = self.amount;
    weakify(self);
    red.selectCompletion = ^(FozWsFJLCFMineWelfareDataModelLetMnJ * _Nonnull VWtWqQdataModelcUgEkM) {
        strongify(self);
        self.welfare = VWtWqQdataModelcUgEkM;
        [self.tableView reloadData];
    };
    [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:red animated:YES];
}

- (UIView *)tableHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FitRealValue(320));
    
    UIView *contentView = [[UIView alloc] init];
    [tableHeaderView addSubview:contentView];
    contentView.backgroundColor = [UIColor whiteColor];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(tableHeaderView);
        make.top.mas_equalTo(tableHeaderView.mas_top).offset(FitRealValue(20));
        make.bottom.mas_equalTo(tableHeaderView.mas_bottom).offset(-FitRealValue(20));
    }];
    
    UILabel *moneyTipsStr = [[UILabel alloc] init];
    [contentView addSubview:moneyTipsStr];
    moneyTipsStr.text = @"￥";
    moneyTipsStr.textColor = [UIColor blackColor];
    moneyTipsStr.font = FONT(26);
    [moneyTipsStr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(contentView.mas_left).offset(FitRealValue(32));
        make.top.mas_equalTo(contentView.mas_top).offset(FitRealValue(48));
        make.height.mas_equalTo(FitRealValue(46));
        make.width.mas_equalTo(30);
    }];
    
    UITextField *HgalTPmoneyFieldNWNbOL = [[UITextField alloc] init];
    HgalTPmoneyFieldNWNbOL.font = FONT(26);
    HgalTPmoneyFieldNWNbOL.textColor = [UIColor blackColor];
    [contentView addSubview:HgalTPmoneyFieldNWNbOL];
    [HgalTPmoneyFieldNWNbOL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(moneyTipsStr.mas_right).offset(FitRealValue(20));
        make.centerY.mas_equalTo(moneyTipsStr.mas_centerY);
        make.height.mas_equalTo(FitRealValue(98));
        make.right.mas_equalTo(contentView.mas_right).offset(-FitRealValue(30));
    }];
    _HgalTPmoneyFieldNWNbOL = HgalTPmoneyFieldNWNbOL;
    
    HgalTPmoneyFieldNWNbOL.keyboardType = UIKeyboardTypeDecimalPad;
    HgalTPmoneyFieldNWNbOL.delegate = self;
    
    UIView *zSVkejgapViewFHHaZg1 = [[UIView alloc] init];
    [contentView addSubview:zSVkejgapViewFHHaZg1];
    zSVkejgapViewFHHaZg1.backgroundColor = LINECOLOR;
    [zSVkejgapViewFHHaZg1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(contentView.mas_left).offset(FitRealValue(32));
        make.right.mas_equalTo(contentView.mas_right).offset(-FitRealValue(32));
        make.height.mas_equalTo(0.5);
        make.top.mas_equalTo(moneyTipsStr.mas_bottom).offset(FitRealValue(48));
    }];
    
    UILabel *allPassLabel = [[UILabel alloc] init];
    [contentView addSubview:allPassLabel];
    allPassLabel.text =  [NSString stringWithFormat:@"剩余可投资金额为 %@ 元", self.CUWORhdetailModelIRREMd.data.remmoney];
    allPassLabel.textColor = QTZ_Gray153;
    allPassLabel.font = FONT(8);
    [allPassLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(contentView.mas_left).offset(FitRealValue(32));
        make.top.mas_equalTo(zSVkejgapViewFHHaZg1.mas_top).offset(FitRealValue(28));
        make.right.mas_equalTo(contentView.mas_right).offset(-FitRealValue(32));
        make.height.mas_equalTo(FitRealValue(24));
    }];
    
    UIView *zSVkejgapViewFHHaZg2 = [[UIView alloc] init];
    [contentView addSubview:zSVkejgapViewFHHaZg2];
    zSVkejgapViewFHHaZg2.backgroundColor = LINECOLOR;
    [zSVkejgapViewFHHaZg2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(contentView.mas_left).offset(FitRealValue(32));
        make.right.mas_equalTo(contentView.mas_right).offset(-FitRealValue(32));
        make.height.mas_equalTo(0.5);
        make.top.mas_equalTo(allPassLabel.mas_bottom).offset(FitRealValue(24));
    }];
    
    UILabel *YBtbRUcanGetLabelfqnRMY = [[UILabel alloc] init];
    [contentView addSubview:YBtbRUcanGetLabelfqnRMY];
    YBtbRUcanGetLabelfqnRMY.textColor = Theme_Color;
    YBtbRUcanGetLabelfqnRMY.font = FONT(8);
    [YBtbRUcanGetLabelfqnRMY mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(contentView.mas_left).offset(FitRealValue(32));
        make.right.mas_equalTo(contentView.mas_right).offset(-FitRealValue(32));
        make.height.mas_equalTo(FitRealValue(24));
        make.top.mas_equalTo(zSVkejgapViewFHHaZg2.mas_bottom).offset(FitRealValue(18));
    }];
    YBtbRUcanGetLabelfqnRMY.text = @"预期收益:";
    _YBtbRUcanGetLabelfqnRMY = YBtbRUcanGetLabelfqnRMY;
    
    return tableHeaderView;
}

- (BOOL)dZrvUEtextFieldRRHEAt:(UITextField *)dZrvUEtextFieldRRHEAt shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *str = [NSString stringWithFormat:@"%@%@", dZrvUEtextFieldRRHEAt.text, string];
    return [self validateNumber:str length:15];
}

- (BOOL)validateNumber:(NSString *)numStr length:(int)length {
    NSString *lengthRegex = [NSString stringWithFormat:@"^[0-9]{0,%d}+$", length];
    NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lengthRegex];
    return [lengthPredicate evaluateWithObject:numStr];
}

- (void)dZrvUEtextFieldRRHEAtDidEndEditing:(UITextField *)dZrvUEtextFieldRRHEAt {
    NSString *text = dZrvUEtextFieldRRHEAt.text;
    
    int amount = text.intValue;
    
    if (amount == self.amount.intValue) {
        return;
    }
    self.welfare = nil;
    
    if (amount > [self.CUWORhdetailModelIRREMd.data.remmoney intValue]) {
        amount = [self.CUWORhdetailModelIRREMd.data.remmoney intValue];
    } else if (amount < [self.CUWORhdetailModelIRREMd.data.lowestAccount intValue]) {
        amount = [self.CUWORhdetailModelIRREMd.data.lowestAccount intValue];
    }
    amount = (amount /100) *100;
    
    NSString *realMoneyStr = [NSString stringWithFormat:@"%d", amount];
    dZrvUEtextFieldRRHEAt.text = realMoneyStr;
    
    self.amount = realMoneyStr;
    
    self.YBtbRUcanGetLabelfqnRMY.text = [NSString stringWithFormat:@"预期收益：%.2f元", amount * [self.CUWORhdetailModelIRREMd.data.apr floatValue] * [self.CUWORhdetailModelIRREMd.data.timeLimitDay integerValue] / 365 / 100];
    
    [self.tableView reloadData];
    
}

@end
